#pragma once
#include <QCoreApplication>
#include <QTcpServer>
#include <QTcpSocket>
#include <QDataStream>

class Server : public QObject 
{
	Q_OBJECT

public:
	Server() 
	{
		server = new QTcpServer(this);
		connect(server, &QTcpServer::newConnection, this, &Server::onNewConnection);
		bool serverStarted = server->listen(QHostAddress::Any, 1234);
		if (!serverStarted) {
			qDebug() << "Server failed to start!";
		}
	}

private slots:
	void onNewConnection() 
	{
		QTcpSocket* clientSocket = server->nextPendingConnection();
		connect(clientSocket, &QTcpSocket::readyRead, this, &Server::onReadyRead);
	}

	void onReadyRead() 
	{
		QTcpSocket* clientSocket = qobject_cast<QTcpSocket*>(sender());
		if (clientSocket) 
		{
			QByteArray data = clientSocket->readAll();
			qDebug() << "Received from client:" << data;
			// Echo the received data back to the client
			clientSocket->write(data);
		}
	}

private:
	QTcpServer* server;
};